package com.atguigu.krp.common.codec;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.krp.common.protocol.ProxyMessage;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import io.netty.handler.codec.MessageToMessageEncoder;
import io.netty.util.CharsetUtil;
import org.springframework.stereotype.Component;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.util.List;

/**
 * @Description 编码器
 * @author KEIO  on 2022/1/12.
 * @version 1.0
 */

public class ProxyMessageEncoder extends MessageToByteEncoder<ProxyMessage> {

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext,
                          ProxyMessage proxyMessage,
                          ByteBuf byteBuf) throws Exception {
        //TODO  java io 的学习
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        DataOutputStream dos = new DataOutputStream(baos);

        int type = proxyMessage.getType();
        dos.writeInt(type);

        JSONObject metaDataJson = new JSONObject(proxyMessage.getMetaData());// 转json再转二进制流
        byte[] metaDataBytes = metaDataJson.toString().getBytes(CharsetUtil.UTF_8);
        dos.writeInt(metaDataBytes.length);
        dos.write(metaDataBytes);

        if(proxyMessage.getData() != null && proxyMessage.getData().length > 0) {
            dos.write(proxyMessage.getData());
        }

        byte[] data = baos.toByteArray();  // 写入bytebuf
        byteBuf.writeInt(data.length);
        byteBuf.writeBytes(data);






    }
}
